<template>
    <section>
        <!-- 工具条 -->
        <el-col :span="24" class="toolbar" style="padding-bottom:0px">
            <el-form :inline="true" :model="filters">
                <el-form-item>
                    <el-input size="small" style="width:200px;" v-model.trim="filters.userId" placeholder="用户名"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-input size="small" style="width:200px;" v-model.trim="filters.mobile" placeholder="手机号"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-select style="width:200px;" clearable v-model="filters.type" size="small" placeholder="用户分类">
                        <el-option label="内部用户" value="0"></el-option>
                        <el-option label="外部用户" value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item style="float:right;">
                    <el-button size="small" v-show="orderAuthExport" type="primary" icon="upload2" @click="">导出</el-button>
                </el-form-item>
                <el-form-item style="float:right;">
                    <el-button size="small" type="primary" icon="search" v-on:click="getAuthUserList(true)" v-show="orderAuthQuery">查询</el-button>
                </el-form-item>
                <!-- <el-form-item style="float:right;">
                    <el-button size="small" type="primary" icon="search" @click="editPermission(scope.$index, scope.row)">修改</el-button>
                </el-form-item> -->
            </el-form>
        </el-col>
        <!-- 工具条 -->

        <!-- 列表 -->
        <el-table :data="authUser" stripe border :height="winHeight-174" highlight-current-row v-loading="listLoading" style="width: 100%;">
            <el-table-column prop="userid" label="用户ID" min-width="100" align="center" sortable="">
            </el-table-column>
            <el-table-column prop='username' label="用户姓名" min-width="100" align="center"></el-table-column>
             <el-table-column prop='type' label="用户类型" min-width="100" align="center" :formatter="formatUserType"></el-table-column>
            <el-table-column prop='mobileno' label="手机号" min-width="100" align="center"></el-table-column>
            <!-- <el-table-column prop='authLevel' label="用户层级" min-width="100" align="center"></el-table-column> -->
            <el-table-column label="操作" min-width="100" align="center" fixed="right">
                <template scope="scope">
                    <el-button size="small" v-show="orderAuthUpdate" @click="editPermission(scope.$index, scope.row)">修改</el-button>
                    <!--  v-show="buttonShow(scope.$index, scope.row)" -->
                    <el-button type="danger"  v-show="orderAuthDetail" size="small" @click="selectPermission(scope.$index, scope.row)">详情</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 列表 -->
        <!--工具条-->
        <el-col :span="24" class="toolbar">
            <el-pagination style="float:right" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page" :page-sizes="[10, 20, 40, 80]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </el-col>

        <!-- 修改界面 -->
        <el-dialog :title="article" v-model="editPermissionVisible" :close-on-click-modal="false">
            <el-form :model="editForm" label-width="120px" ref="editForm">
                <el-row>
                    <el-col :xs="24" :sm="24" :md="12" :lg="12" class="detaillabel">
                        <label class="detailLabel">用户ID:</label>
                        <span class="examineFonts">{{editForm.userid}}</span>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="12" :lg="12" class="detaillabel">
                        <label class="detailLabel">用户名:</label>
                        <span class="examineFonts">{{editForm.username}}</span>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="12" :lg="12" class="detaillabel">

                        <label class="detailLabel">手机号:</label>
                        <span class="examineFonts">{{editForm.mobileno}}</span>
                    </el-col>
                    <!-- <el-col :xs="24" :sm="24" :md="12" :lg="12" class="detaillabel">
                        <label class="detailLabel">用户层级:</label>
                        <span class="examineFonts">{{editForm.authLevel}}</span>
                    </el-col> -->
                </el-row>
                <!--  @check-change="addClickTree" -->
                <!-- <el-tree :data="treedata" :props="defaultProps" ref="tree" show-checkbox node-key="id" :expand-on-click-node="false" :default-expand-all="true" :check-strictly='true' @node-click="handleNodeClick" >
                </el-tree> -->
                <el-tree :data="treedata" show-checkbox :props="defaultProps" node-key="id" @node-click="handleNodeClick" :check-strictly='true' :default-expand-all="true" :expand-on-click-node="false" @check-change="checkChanged" ref="tree" highlight-current></el-tree>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancleBtn">取消</el-button>
                <!--  -->
                <el-button type="primary" v-show='selectPermissionVisibleEE' @click.native="editSubmit" :loading="editLoading">提交</el-button>
            </div>
        </el-dialog>
        <!-- 修改界面 -->

    </section>
</template>


<script>
import util from '../../common/js/util'

import commons from '../../common/js/common'
import { mapState, mapActions } from 'vuex'
//import NProgress from 'nprogress'
import { authUserList, orderAuth, levelList, treeNextChannelList, updateOrderAuth } from '../../api/api';
import common from '../../common/js/common';
export default {
    data() {
        return {
            editPermissionVisible: false,
            selectPermissionVisible: false,
            agentAuthorizeQuery: false,
            listLoading: false,
            editLoading: false,
            orderAuthQuery:false,
            orderAuthDetail:false,
            orderAuthExport:false,
            orderAuthUpdate:false,
            selectPermissionVisibleEE: false,
            article: '',
            leafTree: [],
            page: 1,
            pageSize: 10,
            total: 0,
            exportTotal: 0,
            authUser: [],
            filters: {
                userId: '',
                mobile: '',
                type: '',
            },
            editForm: {
                username: '',
                userid: '',
                mobileno: '',
                authLevel: ''
            },
            treedata: [],
            defaultProps: {
                children: 'children',
                label: 'label'
            }

        }

    },
    methods: {
        // 打开修改界面
        editPermission: function (index, row) {
            this.article = '修改订单查询权限';
            this.editPermissionVisible = true;
            this.selectPermissionVisible = false;
            this.selectPermissionVisibleEE = true;
            this.treedata = [];
            this.getTreeList();
            this.getSelectPerTree(row);
        },
        formatUserType: function (row, column) {
      if (row.type) {
          if (row.type == '0') {
            return '内部';
          }else{
            return '外部';
          }
        }
    },
        getSelectPerTree: function (row) {
            this.editForm = Object.assign({}, row);
            let para = new FormData();
            para.append('userId', row.userid);
            para.append('type', 'channel');
            this.leafTree = [];
            let setCheckedList = [];
            let modelTree = this.treedata;
            orderAuth(para).then((res) => {
                var data = res.data.result;
                for (var k in data) {
                    setTimeout(() => {
                        this.leafTree.push(commons.GetByID(this.treedata, data[k].branchNo));
                    }, 500);
                }
                setTimeout(() => {

                    gettree(data, this.leafTree);
                }, 500);
                setTimeout(() => {
                    this.$refs.tree.setCheckedKeys(setCheckedList);
                }, 1000);
            });
            function gettree(arr, trees) {
                for (var i in arr) {
                    if (typeof (commons.GetByID(trees, arr[i].branchNo)) == 'undefined') {
                        trees.push({
                            id: arr[i].branchNo,
                            label: arr[i].branchCname,
                            children: []
                        });
                    }
                    if (arr[i].nextBranch) {
                        gettree(arr[i].nextBranch, commons.GetByID(trees, arr[i].branchNo).children);
                    }
                    else {
                        setCheckedList.push(arr[i].branchNo);
                    }
                }
            }
        },
        cancleBtn: function () {
            this.editPermissionVisible = false;
            this.selectPermissionVisible = false;
        },
        //修改提交
        editSubmit: function () {
            let checkKeysList = this.$refs.tree.getCheckedKeys();
            let branchNos = '';
            for (var i in checkKeysList) {
                branchNos = branchNos + checkKeysList[i] + ',';
            }
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
                this.editLoading = true;
                let para = new FormData();
                para.append('branchNos', branchNos);
                para.append('userCode', this.editForm.userid);
                updateOrderAuth(para).then((res) => {
                    this.editLoading = false;
                    if (res.data.success) {
                        this.$message({
                            message: '提交成功',
                            type: 'success'
                        });
                        this.$refs['editForm'].resetFields();
                        this.editPermissionVisible = false;
                        this.getAuthUserList(true);
                    }
                    else {
                        this.$message({
                            message: res.data.result,
                            type: 'error'
                        });
                    }
                }).catch(() => {
                    this.editLoading = false;
                });
            });
        },
        handleSizeChange(val) {
            this.pageSize = val;
            this.getAuthUserList(true);
        },
        handleCurrentChange(val) {
            this.page = val;
            this.getAuthUserList(true);
        },
        selectPermission: function (index, row) {
            this.selectPermissionVisible = true;
            this.editPermissionVisible = true;
            this.selectPermissionVisibleEE = false;
            this.article = '权限'
            this.treedata = [];
            this.getTreeList();
            this.getSelectPerTree(row);
        },
        checkChanged:function(data, node, nextNode){
            let arr = data.children;
            for (let i in arr) {
                this.$refs.tree.setChecked(arr[i].id,false,true);
            }
            let checkKeysList = this.$refs.tree.getCheckedKeys();
            console.log(checkKeysList);
        },
        // 点击树形控件返回
        handleNodeClick: function (data, node, obj) {
            let para = new FormData();
            para.append('branchNo', data.id);
            para.append('type', 'level');
            if (this.selectPermissionVisibleEE) {
                treeNextChannelList(para).then((res) => {
                    let treeList = this.treedata;
                    if (res.data.result && res.data.success == true) {
                        for (let i in res.data.result) {
                            let usercode = res.data.result[i].userCode;
                            if (typeof (commons.GetByID(treeList, usercode)) == 'undefined') {
                                const newChild = { id: usercode, label: res.data.result[i].shopName, children: [] };
                                if (!data.children) {
                                    this.$set(data, 'children', []);
                                }
                                 if (typeof (commons.GetByID(treeList, usercode)) == 'undefined') {
                                    data.children.push(newChild);
                                }
                            }
                        }
                    }
                });
            }
        },
        
        // 获取列表数据
        getAuthUserList: function (bool) {
            let para = new FormData();
            para.append("pageSize", bool ? this.pageSize : this.exportTotal);
            para.append("pageNumber", bool ? this.page : 1);
            para.append("userId", this.filters.userId);
            para.append("mobile", this.filters.mobile);
            para.append("type", this.filters.type);
            this.listLoading = bool;
            authUserList(para).then((res) => {
                this.total = res.data.result.totalElements;
                this.exportTotal = res.data.result.totalElements;
                this.listLoading = false;
                this.authUser = res.data.result.content;
            })
        },
        getTreeList: function () {
            let disabledf = this.selectPermissionVisible;
            levelList().then((res) => {
                var data = res.data.result;
                function gettree(arr, trees) {

                    for (var i in arr) {
                        if (disabledf) {
                            trees.push({
                                id: arr[i].branchNo,
                                label: arr[i].branchCname,
                                children: [],
                                // disabled:true
                            });
                        } else {
                            trees.push({
                                id: arr[i].branchNo,
                                label: arr[i].branchCname,
                                children: []
                            });
                        }
                        if (arr[i].nextBranch) {
                            gettree(arr[i].nextBranch, commons.GetByID(trees, arr[i].branchNo).children);
                            // gettree(arr[i].nextBranch, trees[i].children);
                        }
                    }
                }
                gettree(data, this.treedata);
            });
        },

        btnShow: function () {
          let thisData = JSON.parse(sessionStorage.getItem('184'));
          let _this = this;
          $.each(thisData, function (i, j) {
            if (thisData[i] == "orderAuthQuery") {
              _this.orderAuthQuery = true;
            }
            if (thisData[i] == "orderAuthUpdate") {
              _this.orderAuthUpdate = true;
            }
            if (thisData[i] == "orderAuthDetail") {
              _this.orderAuthDetail = true;
            }
            if (thisData[i] == "orderAuthExport") {
              _this.orderAuthExport = true;
            }
          });
        },
    },
    mounted() {
        this.btnShow();
        this.getAuthUserList(true);
    },
    computed: mapState([
        'user',
        'winWidth',
        'winHeight'
    ]),
    // methods

}
</script>
<style scoped>
.detailLabel {
  /*float:left;*/
  display: inline-block;
  text-align: right;
  width: 120px;
  color: #0b80da;
  font-weight: bold;
}
.detaillabel {
  margin-bottom: 10px;
}
</style>